import { customRef, ref } from "vue";

// 防抖
export const debounce = (value: string, delay: number) => {
  let timeout = ref<number | null>(null);
  return customRef((track, trigger) => {
    return {
      get() {
        // 依赖追踪
        track();
        return value;
      },
      set(newValue) {
        clearTimeout(timeout);
        timeout = setTimeout(() => {
          value = newValue;
          //  触发更新
          trigger();
        }, delay);
      },
    };
  });
};
// 节流
export const throttle = (func: any, delay: number) => {
  let shouldExecute = true;
  return function () {
    if (!shouldExecute) return;
    shouldExecute = false;
    func.apply(this, arguments);
    setTimeout(() => {
      shouldExecute = true;
    }, delay);
  };
};
